<template>
  <div>
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        :closable="false"
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon>
      </el-alert>
      <div style="margin: 15px 0;">
        选择商品分类:
        <el-cascader
          v-model="cascaderValue"
          :options="goodsCate"
          :props="cascaderProps"
          @change="cascaderHandleChange">
        </el-cascader>
      </div>
      <!-- tabs标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isDisabled" @click="addParamsDialogVisible = true">添加参数</el-button>
          <el-table :data="manyData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable @close="removeTag(scope.row, index)" v-for="(item, index) in scope.row.attr_vals" :key="index"> {{ item }} </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editParams(scope.row)">修改</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
         <el-button type="primary" size="mini" :disabled="isDisabled" @click="addParamsDialogVisible = true">添加属性</el-button>
         <el-table :data="onlyData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable @close="removeTag(scope.row, index)" v-for="(item, index) in scope.row.attr_vals" :key="index"> {{ item }} </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editParams(scope.row)">修改</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数和添加属性对话框 -->
    <el-dialog
      @close="closeParamsForm"
      :title="'添加' + paramsTitle"
      :visible.sync="addParamsDialogVisible"
      width="50%">
      <!-- 实现表单基本结构 -->
      <el-form :model="addParamsForm" :rules="addParamsFormRules" ref="addParamsRef" label-width="100px">
        <el-form-item  :label="paramsTitle" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsSub">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数和修改属性对话框 -->
    <el-dialog
      :title="'修改' + paramsTitle"
      :visible.sync="editParamsDialogVisible"
      width="50%">
      <el-form :model="editParamsForm" :rules="addParamsFormRules" ref="editParamsRef" label-width="100px">
        <el-form-item :label="paramsTitle" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editparamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsSub">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      goodsCate: [],
      // 双向绑定的级联选择器的值
      cascaderValue: [],
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id'
      },
      activeName: 'many',
      onlyData: [],
      manyData: [],
      addParamsDialogVisible: false,
      addParamsForm: {
        attr_name: ''
      },
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editParamsDialogVisible: false,
      editParamsForm: {
        attr_name: ''
      },
      inputVisible: false,
      inputValue: ''
    }
  },

  created () {
    this.getGoodsCate()
  },

  computed: {
    // 计算按钮是否被禁用
    isDisabled () {
      return this.cascaderValue.length !== 3
    },
    paramsTitle () {
      return this.activeName === 'only' ? '静态属性' : '动态参数'
    },
    cateId () {
      if (this.cascaderValue.length !== 3) {
        return null
      }
      return this.cascaderValue[2]
    }
  },

  methods: {
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.goodsCate = res.data
    },
    // 获取参数
    async getParams () {
      if (this.cascaderValue.length !== 3) {
        this.cascaderValue = []
        this.manyData = []
        this.onlyData = []
        return
      }
      // console.log('选择了第三级')
      // 获取三级分类参数
      // id：三级分类id
      const { data: res } = await this.$axios.get('categories/' + this.cateId + '/attributes', {
        params: {
          sel: this.activeName
        }
      })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      console.log(res.data)
      // 将res.data 数组下的attr_vals字符串转成数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'only') {
        this.onlyData = res.data
      } else {
        this.manyData = res.data
      }
    },
    // 级联选择器选择了
    async cascaderHandleChange () {
      this.getParams()
    },
    // 点击tab标签页每一项
    async handleClick () {
      this.getParams()
    },
    addParamsSub () {
      this.$refs.addParamsRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.post('categories/' + this.cateId + '/attributes', {
          attr_sel: this.activeName,
          attr_name: this.addParamsForm.attr_name
        })
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.addParamsDialogVisible = false
        this.getParams()
        this.$message.success('添加成功')
      })
    },
    closeParamsForm () {
      this.$refs.addParamsRef.resetFields()
    },
    editParams (row) {
      this.editParamsDialogVisible = true
      // console.log(row)
      this.editParamsForm = { ...row }
    },
    // 提交编辑事件
    editParamsSub () {
      this.$refs.editParamsRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
          attr_sel: this.activeName,
          attr_name: this.editParamsForm.attr_name
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        this.$message.success('更新成功')
        this.editParamsDialogVisible = false
        this.getParams()
      })
    },
    deleteParams (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 删除逻辑
        const { data: res } = await this.$axios.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.meta.status === 200) {
          this.$message.success('删除成功')
          this.getParams()
        }
      }).catch(() => {
        this.$message.info('取消删除')
      })
    },
    showInput (row) {
      row.inputVisible = true
      // Vue数据驱动的过程是异步的
      // 代码执行到这里 数据同步了 但是页面还未同步
      // this.$nextTick 数据同步给页面完成更新
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 输入框失去焦点或点击回车
    async handleInputConfirm (row) {
      if (row.inputValue.trim() === '') {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      // console.log('ok')
      row.attr_vals.push(row.inputValue)
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      row.inputVisible = false
      row.inputValue = ''
      this.$message.success('更新成功')
    },
    async removeTag (row, index) {
      row.attr_vals.splice(index, 1)
      const { data: res } = await this.$axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
    }
  }
}
</script>

<style scoped lang='less'>
.el-tag {
  margin: 7px;
}
.input-new-tag {
  width: 120px;
}
</style>
